package pfx;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;

public class Get_Cert_from_pfx {

	/**
	 * 1. 获取 pfx 文件数据
	 * 2. 转换为 字节数组流
	 * 3. 载入 Keystore
	 * 4. 枚举 获取 证书条目
	 * 5. 获取 证书
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		String pfx_path = "C:\\Users\\Administrator\\Desktop\\ttt\\bankside092502.pfx";
		String password = "123456";
		
		get_Cert(pfx_path, password);
		
	}
	public static X509Certificate get_Cert(String pfx_path,String password) throws Exception{
		
		// 存储 证书 和  保存证书
		X509Certificate x509Certificate = null;
		String x509_path = "C:\\Users\\Administrator\\Desktop\\ttt\\Infosec_0927";
		File x509_file = new File(x509_path);
		
		// 读取 pfx 文件信息
		File file = new File(pfx_path);
		byte[] pfx_byte = FileUtils.readFileToByteArray(file);
		
		// 载入 keystore
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		keyStore.load(new ByteArrayInputStream(pfx_byte), password.toCharArray());
		
		// 枚举 得到 合适的证书条目
		Enumeration<String> enums = keyStore.aliases();
		String alia = "";
		
	    
		while(enums.hasMoreElements()){
			alia = enums.nextElement();
			if(keyStore.isKeyEntry(alia)){
				
				x509Certificate = (X509Certificate) keyStore.getCertificate(alia);
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				
				keyStore.store(bos, password.toCharArray());
				byte[] keyStore_byte = bos.toByteArray();
				
				FileUtils.writeByteArrayToFile(x509_file, keyStore_byte);
			}
		}
		
		return x509Certificate;
	}
}











